package com.oocl.jms.parser.impl;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;

import com.oocl.constant.ApplyStatus;
import com.oocl.constant.Constant;
import com.oocl.jms.parser.MessageParser;
import com.oocl.pojo.Application;
import com.oocl.pojo.Merchant;
import com.oocl.pojo.Protocol;
import com.oocl.util.DateUtil;
import com.oocl.util.ImageOutputer;
import com.oocl.util.JSONUtil;
import com.oocl.util.MathUtil;

public class MessageParserImpl implements MessageParser{

	@SuppressWarnings("unchecked")
	@Override
	public Merchant parser(Message message) throws JMSException{
		TextMessage msg = (TextMessage) message;
		Protocol protocol = JSONUtil.toProtocol(msg.getText());
		LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) protocol.getMsgObj();
		Application app = toApplication(map);
		Merchant merchant = writeImage(app);
		return merchant;
	}
	
	public Merchant writeImage(Application app){
		Merchant merchant = null;
		try {
			merchant = new Merchant();
			if(null!=app.getmIdCard() && !"".equals(app.getmIdCard())){
				String idCard = "/idcards"+"/"+app.getmName()+DateUtil.dateToStr(new Date(), "hh-mm-ss")+MathUtil.randowNumber()+".jpg";
				ImageOutputer.output(Constant.IMAGE_DIR+idCard, app.getmIdCard());
				merchant.setIdcard(idCard);
			}
			
			if(null!=app.getmHeadImg() && !"".equals(app.getmHeadImg())){
				String head = "/heads"+"/"+app.getmName()+DateUtil.dateToStr(new Date(), "hh-mm-ss")+MathUtil.randowNumber()+".jpg";
				ImageOutputer.output(Constant.IMAGE_DIR+head, app.getmHeadImg());
				merchant.setHeading(head);
			}
			merchant.setId(app.getmId());
			merchant.setName(app.getmName());
			merchant.setAddress(app.getmAddr());
			merchant.setBan(false);
			merchant.setStatus(ApplyStatus.PENGDING);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return merchant;
	}

	private Application toApplication(LinkedHashMap<String, Object> map) {
		Application app = new Application();
		app.setmId((String)map.get("mId"));
		app.setmName((String)map.get("mName"));
		app.setmIdCard((String)map.get("mIdCard"));
		app.setmHeadImg((String)map.get("mHeadImg"));
		app.setmAddr((String)map.get("mAddr"));
		app.setmStatus(ApplyStatus.PENGDING);
		app.setBan(false);
		return app;
	}

}
